package luj.tool.jnproxyan.proxy.admin.http.handle.invoke;

import com.google.common.collect.ImmutableMap;
import io.vertx.core.AsyncResult;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpHeaders;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.common.template.TemplateEngine;
import luj.tool.jnproxyan.proxy.admin.AdminHttpModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

final class HttpPageResponser {

  HttpPageResponser(RoutingContext vertx, TemplateEngine freeMarker, Map<String, Object> model, AdminHttpModule rootModule, String routePath) {
    _vertx = vertx;
    _freeMarker = freeMarker;
    _model = model;
    _rootModule = rootModule;
    _routePath = routePath;
  }

  void response() {
    String rootPath = _rootModule.path();
    String ftlSub = _routePath.substring(rootPath.length());

    String ftlFull = TEMPLATE_DIR + "/module/" + ftlSub
        .replaceFirst("^/?", "")
        .replaceAll("/:[^/]+", "");

    String common = TEMPLATE_DIR + "/common";
//    LOG.debug("{} {}", ftlFull, false);// Files.isRegularFile(ftlFull));

    Map<String, Object> ftlVar = ImmutableMap.of("common", common);
    _freeMarker.render(ImmutableMap.<String, Object>builder()
        .put("ftl", ftlVar)
        .putAll(_model).build(), ftlFull, this::finishRender);
  }

  private void finishRender(AsyncResult<Buffer> res) {
    if (!res.succeeded()) {
      _vertx.fail(res.cause());
      return;
    }

    _vertx.response()
        .putHeader(HttpHeaders.CONTENT_TYPE, "text/html")
        .end(res.result());
  }

  //  private static final Logger LOG = LoggerFactory.getLogger(HttpPageResponser.class);
  private static final String TEMPLATE_DIR = "/page";

  private final RoutingContext _vertx;

  private final TemplateEngine _freeMarker;
  private final Map<String, Object> _model;

  private final AdminHttpModule _rootModule;
  private final String _routePath;
}
